"""
管理后台 - 场地管理接口
"""
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_, func
from typing import Optional, List
from pydantic import BaseModel
from datetime import datetime

from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.core.permissions import require_permission, Permission, UserRole, check_permission
from app.models.user import User
from app.models.venue import Venue
from app.schemas.common import ApiResponse
from app.utils.helpers import generate_id
from loguru import logger

router = APIRouter(prefix="/venue", tags=["管理后台-场地"])


class VenueListResponse(BaseModel):
    """场地列表响应"""
    list: List[dict]
    total: int
    page: int
    pageSize: int


class VenueCreateRequest(BaseModel):
    """创建场地请求"""
    name: str
    type: List[str]  # ['5人', '7人', '11人']
    cityId: Optional[str] = None
    cityName: str
    address: str
    lat: float
    lng: float
    contactPhone: str
    businessHours: str
    images: List[str]  # 图片URL列表
    facilities: List[str]  # 设施列表 ['parking', 'shower', 'locker']
    grassType: Optional[str] = None  # 草皮类型
    hasCover: bool = False  # 是否有顶棚
    hasLight: bool = False  # 是否有灯光
    description: Optional[str] = None
    priceRange: Optional[str] = None
    priceNote: Optional[str] = None
    isRecommended: bool = False
    status: str = "operating"  # operating, closed, maintenance


@router.get("/list", response_model=ApiResponse[VenueListResponse])
async def get_venue_list(
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
    keyword: Optional[str] = Query(None),
    city: Optional[str] = Query(None),
    status: Optional[str] = Query(None),
    auditStatus: Optional[str] = Query(None),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取场地列表
    支持关键词搜索、城市筛选、状态筛选
    """
    logger.info(f"📋 获取场地列表: page={page}, keyword={keyword}, city={city}")
    
    # 检查权限
    user_role = getattr(current_user, 'role', 'user')
    
    # 基础查询
    query = db.query(Venue)
    
    # 城市管理员只能看到自己城市的场地
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city:
            query = query.filter(
                or_(Venue.city_name == user_city, Venue.city_id == user_city)
            )
            logger.info(f"🏙️  城市管理员筛选: {user_city}")
    
    # 关键词搜索
    if keyword:
        query = query.filter(
            or_(
                Venue.name.like(f"%{keyword}%"),
                Venue.address.like(f"%{keyword}%")
            )
        )
    
    # 城市筛选
    if city:
        query = query.filter(
            or_(Venue.city_name == city, Venue.city_id == city)
        )
    
    # 状态筛选
    if status:
        query = query.filter(Venue.status == status)
    
    # 审核状态筛选
    if auditStatus:
        query = query.filter(Venue.audit_status == auditStatus)
    
    # 总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * pageSize
    venues = query.order_by(Venue.created_at.desc()).offset(offset).limit(pageSize).all()
    
    # 转换为字典
    venue_list = []
    for venue in venues:
        venue_dict = venue.to_dict()
        # 添加创建者信息
        if venue.creator_id:
            creator = db.query(User).filter(User.id == venue.creator_id).first()
            if creator:
                venue_dict['creatorName'] = creator.nick_name
                venue_dict['creatorPhone'] = creator.phone
        venue_list.append(venue_dict)
    
    logger.success(f"✅ 返回场地列表: total={total}, count={len(venue_list)}")
    
    return ApiResponse(data={
        "list": venue_list,
        "total": total,
        "page": page,
        "pageSize": pageSize
    })


@router.post("/create", response_model=ApiResponse[dict])
@require_permission(Permission.VENUE_CREATE)
async def create_venue(
    request: VenueCreateRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    创建场地
    城市管理员只能创建自己城市的场地
    """
    logger.info(f"➕ 创建场地: {request.name}, 城市: {request.cityName}")
    
    user_role = getattr(current_user, 'role', 'user')
    
    # 城市管理员检查城市权限
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city and user_city != request.cityName:
            raise HTTPException(403, "只能创建自己负责城市的场地")
    
    # 创建场地
    venue = Venue(
        id=generate_id(),
        name=request.name,
        type=','.join(request.type),
        city_id=request.cityId,
        city_name=request.cityName,
        address=request.address,
        lat=request.lat,
        lng=request.lng,
        contact_phone=request.contactPhone,
        business_hours=request.businessHours,
        images=','.join(request.images) if request.images else None,
        facilities=','.join(request.facilities) if request.facilities else None,
        grass_type=request.grassType,
        has_cover=request.hasCover,
        has_light=request.hasLight,
        description=request.description,
        price_range=request.priceRange,
        price_note=request.priceNote,
        is_recommended=request.isRecommended,
        status=request.status,
        creator_type='city_manager' if user_role == 'city_manager' else 'system',
        creator_id=current_user.id,
        audit_status='approved' if user_role == 'super_admin' else 'pending',
        view_count=0,
        favorite_count=0
    )
    
    db.add(venue)
    db.commit()
    db.refresh(venue)
    
    logger.success(f"✅ 场地创建成功: {venue.id} - {venue.name}")
    
    return ApiResponse(data=venue.to_dict(), message="场地创建成功")


@router.get("/{venue_id}", response_model=ApiResponse[dict])
async def get_venue_detail(
    venue_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取场地详情"""
    venue = db.query(Venue).filter(Venue.id == venue_id).first()
    if not venue:
        raise HTTPException(404, "场地不存在")
    
    # 城市管理员权限检查
    user_role = getattr(current_user, 'role', 'user')
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city and venue.city_name != user_city:
            raise HTTPException(403, "无权查看其他城市的场地")
    
    venue_dict = venue.to_dict()
    
    # 添加创建者信息
    if venue.creator_id:
        creator = db.query(User).filter(User.id == venue.creator_id).first()
        if creator:
            venue_dict['creatorName'] = creator.nick_name
            venue_dict['creatorPhone'] = creator.phone
    
    return ApiResponse(data=venue_dict)


@router.put("/{venue_id}", response_model=ApiResponse[dict])
@require_permission(Permission.VENUE_EDIT_ALL, Permission.VENUE_EDIT_CITY)
async def update_venue(
    venue_id: str,
    request: VenueCreateRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新场地信息"""
    logger.info(f"✏️  更新场地: {venue_id}")
    
    venue = db.query(Venue).filter(Venue.id == venue_id).first()
    if not venue:
        raise HTTPException(404, "场地不存在")
    
    # 城市管理员权限检查
    user_role = getattr(current_user, 'role', 'user')
    if user_role == 'city_manager':
        user_city = getattr(current_user, 'city_name', None) or getattr(current_user, 'city_id', None)
        if user_city and venue.city_name != user_city:
            raise HTTPException(403, "无权编辑其他城市的场地")
    
    # 更新字段
    venue.name = request.name
    venue.type = ','.join(request.type)
    venue.city_id = request.cityId
    venue.city_name = request.cityName
    venue.address = request.address
    venue.lat = request.lat
    venue.lng = request.lng
    venue.contact_phone = request.contactPhone
    venue.business_hours = request.businessHours
    venue.images = ','.join(request.images) if request.images else None
    venue.facilities = ','.join(request.facilities) if request.facilities else None
    venue.grass_type = request.grassType
    venue.has_cover = request.hasCover
    venue.has_light = request.hasLight
    venue.description = request.description
    venue.price_range = request.priceRange
    venue.price_note = request.priceNote
    venue.is_recommended = request.isRecommended
    venue.status = request.status
    
    db.commit()
    db.refresh(venue)
    
    logger.success(f"✅ 场地更新成功: {venue_id}")
    
    return ApiResponse(data=venue.to_dict(), message="场地更新成功")


@router.delete("/{venue_id}", response_model=ApiResponse[str])
@require_permission(Permission.VENUE_DELETE)
async def delete_venue(
    venue_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除场地（仅超管）"""
    logger.info(f"🗑️  删除场地: {venue_id}")
    
    venue = db.query(Venue).filter(Venue.id == venue_id).first()
    if not venue:
        raise HTTPException(404, "场地不存在")
    
    db.delete(venue)
    db.commit()
    
    logger.success(f"✅ 场地删除成功: {venue_id}")
    
    return ApiResponse(message="场地删除成功")


class VenueAuditRequest(BaseModel):
    """场地审核请求"""
    action: str  # approve, reject
    note: Optional[str] = None


@router.post("/{venue_id}/audit", response_model=ApiResponse[str])
@require_permission(Permission.VENUE_AUDIT)
async def audit_venue(
    venue_id: str,
    request: VenueAuditRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """审核场地（仅超管）"""
    logger.info(f"✅ 审核场地: {venue_id}, action: {request.action}")
    
    venue = db.query(Venue).filter(Venue.id == venue_id).first()
    if not venue:
        raise HTTPException(404, "场地不存在")
    
    if request.action == 'approve':
        venue.audit_status = 'approved'
        message = "场地审核通过"
    elif request.action == 'reject':
        venue.audit_status = 'rejected'
        message = "场地审核拒绝"
    else:
        raise HTTPException(400, "无效的审核操作")
    
    venue.audit_note = request.note
    venue.audited_by = current_user.id
    venue.audited_at = datetime.now()
    
    db.commit()
    
    logger.success(f"✅ 场地审核成功: {venue_id}, action: {request.action}")
    
    return ApiResponse(message=message)

